package com.weijing.pretty_app.activity

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weijing.pretty_app.adapter.DevicesAdapter
import com.weijing.pretty_app.databinding.ActivityBluethoothBinding
import com.weijing.pretty_app.util.BluetoothSocketManager
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.SPUtil
import com.weijing.pretty_app.util.ToastUtils
import java.io.IOException
import java.io.InputStream

private const val TAG = "BluetoothActivity"

class BluetoothActivity : BaseActivity() {

    private val binding by lazy { ActivityBluethoothBinding.inflate(layoutInflater) }
    override fun getMainView(): View = binding.main
    private var isReceiverRegistered = false
    private var mAdapter: DevicesAdapter? = null
    private lateinit var bluetoothAdapter: BluetoothAdapter
    private val foundDevices = mutableListOf<BluetoothDevice>()
    private val requiredPermissions: Array<String>
        get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
        } else {
            arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.ACCESS_FINE_LOCATION)
        }
    private var pendingDeviceToConnect: BluetoothDevice? = null
    private var bluetoothSocket: BluetoothSocket? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initBluetooth()
        initClick()
        initAdapter()
    }

    private fun initClick() {
        binding.bluetoothIvBack.setOnClickListener { finish() }

        LiveEventBus.get<String>(KeyUtil.NOTICE_DEVICE_ID).observeSticky(this, { id ->
            if (!id.isNullOrEmpty()) {
                mAdapter?.noticeAddress(id)
            }
        })

        /*LiveEventBus.get<String>(KeyUtil.CLOSE_BLUETOOTH_ACTIVITY).observeSticky(this) {
            Log.i(TAG, "收到关闭页面的通知了-- $it ")
            LiveEventBus.get<Boolean>(KeyUtil.BLUETOOTH_CONNECT_TRUE).post(true)
            finish()
        }*/
    }

    private fun initBluetooth() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

        if (!hasPermissions()) {
            requestPermissions(requiredPermissions, 1001)
            return
        }
        ensureBluetoothEnabled()
        registerBluetoothReceiverIfNeeded()
    }


    private fun hasPermissions(): Boolean {
        return requiredPermissions.all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }
    }

    private fun startDiscovery() {
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
            ToastUtils.show("设备不支持蓝牙")
            return
        }

        val hasScanPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.BLUETOOTH_SCAN
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        }

        if (!hasScanPermission) {
            ToastUtils.show("缺少扫描权限")
            return
        }

        foundDevices.clear()
        mAdapter?.updateDevices(emptyList())

        if (bluetoothAdapter.isDiscovering) {
            bluetoothAdapter.cancelDiscovery()
        }

        bluetoothAdapter.startDiscovery()
    }

    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device =
                        intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    if (device != null && !foundDevices.contains(device)) {
                        foundDevices.add(device)
                        mAdapter?.updateDevices(foundDevices.toList())
                    }
                }

                //配对状态
                BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                    val device =
                        intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    // 检查权限再访问 device 信息
                    if (device != null &&
                        ContextCompat.checkSelfPermission(
                            this@BluetoothActivity, Manifest.permission.BLUETOOTH_CONNECT
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        Log.i(TAG, "onReceive状态呢: ${device.bondState}")

                        when (device.bondState) {
                            BluetoothDevice.BOND_BONDING -> {
                                ToastUtils.show("正在配对：${device.name}")
                            }

                            BluetoothDevice.BOND_BONDED -> {
                                ToastUtils.show("配对成功：${device.name}")
                                // 自动连接
                                if (device == pendingDeviceToConnect) {
                                    connectToDevice(device)
                                    pendingDeviceToConnect = null
                                }
                            }

                            BluetoothDevice.BOND_NONE -> {
                                ToastUtils.show("配对取消或失败：${device.name}")
                            }
                        }
                    } else {
                        ToastUtils.show("无权限访问配对状态")
                    }
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1001 && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
            ensureBluetoothEnabled()
            registerBluetoothReceiverIfNeeded()
            pendingDeviceToConnect?.let {
                connectToDevice(it)
                pendingDeviceToConnect = null
            }
        } else {
            ToastUtils.show("需要蓝牙权限")
        }
    }

    private fun registerBluetoothReceiverIfNeeded() {
        if (!isReceiverRegistered) {
            val filter = IntentFilter(BluetoothDevice.ACTION_FOUND).apply {
                addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
            }
            registerReceiver(receiver, filter)
            isReceiverRegistered = true
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1002) {
            if (resultCode == Activity.RESULT_OK) {
                // 用户同意开启蓝牙，继续扫描
                startDiscovery()
            } else {
                ToastUtils.show("蓝牙未开启，无法扫描")
            }
        }
    }

    private fun initAdapter() {
        mAdapter = DevicesAdapter()
        mAdapter?.onClickListener = object : DevicesAdapter.OnClickListener {
            override fun onItemClickListener(device: BluetoothDevice) {
//                BluetoothSPPManager.connect(device.address)
//                connectToDevice(device)
                if (!hasPermissions()) {
                    pendingDeviceToConnect = device
                    requestPermissions(requiredPermissions, 1001)
                } else {
                    connectToDevice(device)
                }
            }
        }
        binding.bluetoothRV.adapter = mAdapter
    }

    private fun ensureBluetoothEnabled() {
        if (bluetoothAdapter.isEnabled) {
            startDiscovery()
            return
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_CONNECT
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ToastUtils.show("缺少蓝牙连接权限")
                return
            }
        } else {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ToastUtils.show("缺少蓝牙权限")
                return
            }
        }

        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivityForResult(enableBtIntent, 1002)
    }

    //配对设备
    private fun pairDevice(device: BluetoothDevice) {
        val hasPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) ==
                    PackageManager.PERMISSION_GRANTED
        } else {
            ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) ==
                    PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION
                    ) ==
                    PackageManager.PERMISSION_GRANTED
        }

        if (!hasPermission) {
            ToastUtils.show("缺少配对权限")
            return
        }

        try {
            if (device.bondState == BluetoothDevice.BOND_NONE) {
                val paired = device.createBond()
                if (!paired) {
                    ToastUtils.show("配对请求发起失败")
                }
            } else {
                ToastUtils.show("设备已配对")
            }
        } catch (e: SecurityException) {
            e.printStackTrace()
            ToastUtils.show("没有权限执行配对")
        }
    }

    private fun connectToDevice(device: BluetoothDevice) {
        BluetoothSocketManager.closeConnection()
        BluetoothSocketManager.connect(this, device, onResult = { flag_, msg ->
            if (flag_) {
                Log.i(TAG, "连接成功关闭页面了")
                LiveEventBus.get<Boolean>(KeyUtil.BLUETOOTH_CONNECT_TRUE).post(true)
                SPUtil.put(KeyUtil.DEVICE_ADDRESS, device.address)
                finish()
            }
        })
    }
    /*private fun connectToDevice(device: BluetoothDevice) {
        Thread {
            try {
                if (ActivityCompat.checkSelfPermission(
                        this, Manifest.permission.BLUETOOTH
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    runOnUiThread { ToastUtils.show("缺少蓝牙权限") }
                    return@Thread
                }

                // 常用串口通信 UUID
                val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")

                val socket = device.createRfcommSocketToServiceRecord(uuid)

                Log.i(TAG, "connectToDevice连接状态: ${socket.isConnected}")
                // 停止发现以防影响连接
                bluetoothAdapter.cancelDiscovery()

                if (socket.isConnected) {
                    ToastUtils.show("蓝牙已经在连接状态 !")
                    return@Thread
                }
                socket.connect() // ⚠️ 这里会阻塞线程
                bluetoothSocket = socket
                startReading(socket.inputStream)
                runOnUiThread {
                    SPUtil.put(KeyUtil.DEVICE_ID, device.address)
                    ToastUtils.show("蓝牙连接成功")
                }
            } catch (e: IOException) {
                e.printStackTrace()
                runOnUiThread {
                    ToastUtils.show("连接失败: ${e.message}")
                }
            }
        }.start()
    }*/

    private fun startReading(inputStream: InputStream) {
        Thread {
            Log.i(TAG, "startReading: 进来了吗")
            val buffer = ByteArray(1024)
            try {
                while (!Thread.currentThread().isInterrupted) {
                    val bytesRead = inputStream.read(buffer)
                    if (bytesRead > 0) {
                        val data = buffer.copyOf(bytesRead)
                        val hexString = data.joinToString(" ") { "%02X".format(it) }
                        Log.d(TAG, "收到数据11: $hexString")
                        // 通过事件广播或回调传递数据给 Activity
                    } else {
                        Log.w(TAG, "读取到 -1，连接已关闭")
                        handleSocketDisconnected()
                        break
                    }
                }
            } catch (e: IOException) {
                handleSocketDisconnected()
                Log.e(TAG, "读取失败: ${e.message}")
            }
        }.start()
    }

    private fun handleSocketDisconnected() {
        try {
            bluetoothSocket?.close()
        } catch (e: IOException) {
            Log.e(TAG, "关闭 socket 时出错: ${e.message}")
        }
        bluetoothSocket = null

        runOnUiThread {
            ToastUtils.show("蓝牙连接已断开")
            // 你也可以发 LiveEventBus 通知 UI 状态变化
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isReceiverRegistered) {
            unregisterReceiver(receiver)  // ✅ 只在注册过时反注册
            isReceiverRegistered = false
        }
        if (ActivityCompat.checkSelfPermission(
                this, Manifest.permission.BLUETOOTH_SCAN
            ) == PackageManager.PERMISSION_GRANTED &&
            bluetoothAdapter.isDiscovering
        ) {
            bluetoothAdapter.cancelDiscovery()
        }
    }
}